package com.yingxin.yx.framework.commons.utlis;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 对象序列化，反序列化
 */

public class ObjectSerializationUtils {

    private static ByteArrayOutputStream byteArrayOutputStream = null;

    private static ObjectOutputStream objectOutputStream = null;

    private static ByteArrayInputStream byteArrayInputStream = null;

    private static ObjectInputStream objectInputStream = null;

    private static void initOut() throws IOException {
        byteArrayOutputStream = new ByteArrayOutputStream();
        objectOutputStream = new ObjectOutputStream( byteArrayOutputStream );
    }

    private static void initInput(String serialization) throws IOException {
        byteArrayInputStream = new ByteArrayInputStream( serialization.getBytes( StandardCharsets.ISO_8859_1 ) );
        objectInputStream = new ObjectInputStream( byteArrayInputStream );
    }

    private static String getString() throws IOException {
        objectOutputStream.flush();
        byte[] data = byteArrayOutputStream.toByteArray();
        return new String( data, StandardCharsets.ISO_8859_1 );
    }

    /**
     * 序列化对象
     */
    public static <T> String objectToSerialization(T obj){
        try{
            initOut();
            objectOutputStream.writeObject( obj );
            return getString();
        }catch (Exception e){ }
        return null;
    }

    /**
     * 序列化集合
     */
    public static <T> String listToSerialization(List<T> listObjects){
        try{
            initOut();
            objectOutputStream.writeObject( listObjects );
            return getString();
        }catch (Exception e){ }
        return null;
    }

    /**
     * 反序列化对象
     */
    public static <T> T serializationToObject(String serialization) throws IOException, ClassNotFoundException {
        initInput( serialization );

        return (T) objectInputStream.readObject();
    }

    /**
     * 反序列化集合
     */
    public static <T> List<T> serializationToList(String serialization) throws IOException, ClassNotFoundException {
        initInput( serialization );

        return (List<T>) objectInputStream.readObject();
    }
}
